package com.simplehc7878.auth.common;

import com.simplehc7878.auth.common.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class EnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return source -> {
            T[] enumConstants = targetType.getEnumConstants();
            for (T enumConstant : enumConstants) {
                if (Objects.equals(String.valueOf(enumConstant.getCode()), source)) {
                    return enumConstant;
                }
            }
            throw new IllegalArgumentException("枚举值:" + source + "，不支持");
        };
    }
}
